import requests
from requests.exceptions import RequestException
import re
import json
from multiprocessing import Pool
import MySQLdb


class MysqlHelper:

    def __init__(self, host='127.0.0.1', port=3306, user='root', passwd='1234567', db='spiderdb', charset='utf8'):

        self.__conn = MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset)

        cur = self.__conn.cursor()

        cur.execute("""
        create table if not exists `movies`(
            `mid` int primary key autoincrement,
            `title` varchar(40),
            `actor` varchar(40),
            `time` date,
            `score` float
            )
        """)

    def insert(self, title1, actor1, time1, score1):
        cur = self.__conn.cursor()

        cur.execute("insert into `movies` value ('{}', '{}', '{}', '{}')".format(title1, actor1, time1, score1))
        self.__conn.commit()
        cur.close()
        self.__conn.close()


headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
}

login_url = "http://www.maoyan.com/login"

def get_one_page(url):
    try:
        # session = requests.Session()
        # response = session.get(login_url, data={"username": "john"})
        # # TODO: test if response is ok
        # response = session.get(url)

        # 获取网页html内容
        response = requests.get(url, headers=headers)
        # 通过状态码判断是否获取成功
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None


def parse_one_page(html):
    # 正则表达式进行解析
    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name">'
                         + '<a.*?>(.*?)</a>.*?"star">(.*?)</p>.*?releasetime">(.*?)</p>'
                         + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
    # 匹配所有符合条件的内容
    items = re.findall(pattern, html)
    for item in items:
        yield {
            # 'index': item[0],
            # 'image': item[1],
            'title': item[2],
            'actor': item[3].strip()[3:],
            'time': item[4].strip()[5:],
            'score': item[5] + item[6]
        }


def write_to_file(content):
    with open('result.csv', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')
        f.close()


def main(offset):
    url = 'http://maoyan.com/board/4?offset=' + str(offset)
    html = get_one_page(url)
    mysqldb = MysqlHelper()

    for item in parse_one_page(html):
        print(item)
        # write_to_file(item)
        mysqldb.insert(item['title'], item['actor'], item['time'], item['score'])


if __name__ == '__main__':
    # for i in range(10):
    #      main(i * 10)
    pool = Pool()
    pool.map(main, [i * 10 for i in range(10)])
